const uniID = require('uni-id')
const config = require('config')
var CryptoJS = require("crypto-js");
var SHA256 = require("crypto-js/hmac-sha256");
var dbUtil = require("db-util")
let db = uniCloud.database()
let dbCmd = db.command
module.exports = {
	_before: async function () { // 通用预处理器
		const token = this.getUniIdToken()
		if (!token) {
			throw new Error('未登录')
		}
		const payload = await uniID.checkToken(token)
		let {
			code,
			uid,
			permission,
			userInfo
		} = payload
		if (code) {
			throw new Error('未登录')
		}
		this.uid = uid
		this.wx_openid = userInfo.wx_openid ? userInfo.wx_openid.mp : ''
		this.userInfo = userInfo
		if (!permission) {
			permission = await uniID.getPermissionByUid({
				uid
			})
		}
		this.permission = permission
		let roleRes = await uniID.getRoleByUid({
			uid
		})
		if (roleRes.code != 0) {
			throw new Error(roleRes.msg)
		}
		this.roles = roleRes.role
		const methodName = this.getMethodName()
		let isAdmin = this.roles.some(item => item == 'admin')
		if (methodName == 'checkAuth' && this.permission.indexOf('auth:check') == -1 && !isAdmin) {
			throw new Error('无权限')
		}
	},
	
	async getMyAuthInfo() {
		let userInfo = await dbUtil.getById({
			collection: 'uni-id-users',
			id: this.uid,
			field: {
				realname_auth: true
			}
		})
		return userInfo.realname_auth || null
	},
	 
	async genAuthReqParams() {
		var salt = CryptoJS.lib.WordArray.random(128 / 8);
		console.log('salt', salt)
		let nonceStr = CryptoJS.enc.Base64.stringify(salt);
		console.log('nonceStr', nonceStr)
		let p = {
			api_version: '1.0',
			mch_id: config.wxConfigMp.mchId,
			appid: config.wxConfigMp.appId,
			response_type: 'code',
			scope: 'pay_identity',
			openid: this.wx_openid,
			nonce_str: nonceStr,
			sign_type: 'HMAC-SHA256',
			
		}
		let keys = Object.keys(p)
		keys.sort()
		console.log('keys', keys);
		let strSignTemp = keys.map(key => {
			return `${key}=${p[key]}`
		}).concat([`key=${config.wxConfigMp.key}`]).join('&')
		console.log('strSignTemp', strSignTemp)
		let sign = SHA256(strSignTemp, config.wxConfigMp.key)
		let sign2 = CryptoJS.enc.Hex.stringify(sign).toUpperCase()
		console.log('sign', sign2)
		p.sign = sign2
		return p
	},
	
	async commitIDInfo({
		realname,
		identity,
		gender,
		idCardFront,
		idCardBack,
		latestHeadImg,
		extraImgs
	}) {
		if (!realname || !identity || gender == undefined || (gender != 0 && gender != 1) || !extraImgs || !extraImgs.length) {
			return {
				errCode: 500,
				errMsg: '参数错误'
			}
		}
		if (this.userInfo.realname_auth && this.userInfo.realname_auth.auth_status != 0 && this.userInfo.realname_auth.auth_status != 3) {
			return {
				errCode: 501,
				errMsg: '等待审核中，请勿重复提交？'
			}
		}
		let realname_auth = {
			type: 0,
			auth_status: 1,
			real_name: realname,
			identity,
			gender,
			id_card_front: idCardFront,
			id_card_back: idCardBack,
			latestHeadImg,
			extraImgs
		}
		await dbUtil.updateById({
			collection: 'uni-id-users',
			data: {
				_id: this.userInfo._id,
				realname_auth
			}
		})
		return realname_auth
	},
	
	async checkAuth({
		uid,
		status = 2
	}) {
		let userInfo = await dbUtil.getById({
			collection: 'uni-id-users',
			id: uid
		})
		if (!userInfo.realname_auth || userInfo.realname_auth.auth_status != 1) {
			return {
				errCode: 501,
				errMsg: '用户未提交资料或已审核！'
			}
		}
		await dbUtil.updateById({
			collection: 'uni-id-users',
			data: {
				_id: uid,
				realname_auth: {
					auth_status: status,
					auth_date: Date.now()
				}
			}
		})
	}
}
